package com.streambolics.mail;

import java.util.Properties;

import javax.activation.DataHandler;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.util.ByteArrayDataSource;

public class SendMail
{
    private static Session _Session;

    public static void addBody (Multipart aMultipart, EmailTextBuilder aBody) throws Exception
    {
        addHtml (aMultipart, aBody.getHtmlString ());
        addPlainText (aMultipart, aBody.getPlainString ());
    }

    public static void addCalendar (Multipart aMultipart, String aCaltext) throws Exception
    {
        BodyPart p = new MimeBodyPart ();
        p.setHeader ("Content-Class", "urn:content-classes:calendarmessage");
        p.setHeader ("Content-ID", "calendar_message");
        p.setDataHandler (new DataHandler (new ByteArrayDataSource (aCaltext, "text/calendar")));
        p.setFileName ("calendar.ics");
        aMultipart.addBodyPart (p);
    }

    public static void addHtml (Multipart aMultipart, String aHtml) throws Exception
    {
        addPart (aMultipart, "text/html", aHtml);
    }

    public static void addPart (Multipart aMultipart, String aMimeType, String aText) throws Exception
    {
        BodyPart p = new MimeBodyPart ();
        p.setContent (aText, aMimeType);
        aMultipart.addBodyPart (p);
    }

    public static void addPlainText (Multipart aMultipart, String aText) throws Exception
    {
        addPart (aMultipart, "text/plain", aText);
    }

    public static Message createMessage (String aFromEmail, String aFromName, String aToEmail, String aToName) throws Exception
    {
        Message msg = new MimeMessage (getSession ());
        msg.setFrom (new InternetAddress (aFromEmail, aFromName));
        msg.addRecipient (Message.RecipientType.TO, new InternetAddress (aToEmail, aToName));
        return msg;
    }

    public static Session getSession ()
    {
        if (_Session == null)
        {
            Properties props = new Properties ();
            _Session = Session.getDefaultInstance (props, null);
        }
        return _Session;
    }

    public static void sendMessage (Message aMessage) throws Exception
    {
        Transport.send (aMessage);
    }
}
